package com.sat.seckill.timer;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sat.common.entity.DateUtil;
import com.sat.seckill.mapper.SeckillMapper;
import com.sat.seckill.model.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class SeckillGoodsPushTask {

int i=0;
//    @Scheduled(cron = "0/5 * * * * ? ")//标记这个方法每五秒执行一次
//    public void test1(){
//        i++;
//        System.out.println(i);
//    }

    @Autowired
    private SeckillMapper seckillMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 从数据库查询出秒杀的商品存入到redis
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void pushTaskToRedis(){
        //这里获得的是从当前时间开始两小时拍卖的时间
        List<Date> dateMenus = DateUtil.getDateMenus();
        //删除当前拍卖的时间段，从下一次拍卖开始获取数据
        dateMenus.remove(0);
        for (Date dateMenu : dateMenus) {


            QueryWrapper<SeckillGoods> queryWrapper=new QueryWrapper<>();
            //状态为1表示审核通过，允许进行秒杀
            queryWrapper.eq("status","1");
            //获取拍卖时间段的商品（不包括当前拍卖时间段）
            queryWrapper.ge("start_time",dateMenu);//拍卖开始时间
            queryWrapper.lt("end_time",DateUtil.addDateHour(dateMenu,2));
            List<SeckillGoods> seckillGoods = seckillMapper.selectList(queryWrapper);
            //将数据放到redis里面去
            BoundHashOperations boundHashOperations = redisTemplate.boundHashOps("seckill_" + DateUtil.date2Str(dateMenu));
            for (SeckillGoods seckillGood : seckillGoods) {
                //把秒杀的商品的具体信息保存到redis
                boundHashOperations.put(seckillGood.getId(),seckillGood);
            }
//            System.out.println(seckillGoods);
//            System.out.println(DateUtil.date2Str(dateMenu));

        }


    }
}
